<template>
  <div class="organization-switcher" v-if="storeUserOrganizations.length > 1">
    <el-dropdown @command="handleOrganizationChange" trigger="click">
      <el-button class="organization-button" type="primary" plain>
        <el-icon><OfficeBuilding /></el-icon>
        <span class="organization-name">{{ storeCurrentOrganization?.name || '请选择组织' }}</span>
        <el-icon class="el-icon--right"><ArrowDown /></el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu class="organization-dropdown">
          <el-dropdown-item 
            v-for="org in storeUserOrganizations" 
            :key="org.id" 
            :command="org.id"
            :disabled="org.id === storeCurrentOrganization?.id"
            class="organization-dropdown-item"
          >
            <div class="org-item">
              <el-avatar :size="24" :src="org.avatar" class="org-avatar">
                {{ org.name.charAt(0) }}
              </el-avatar>
              <div class="org-info">
                <div class="org-name">{{ org.name }}</div>
                <div class="org-role">{{ getUserRoleInOrganization(org.id) }}</div>
              </div>
            </div>
          </el-dropdown-item>
          <el-dropdown-item divided>
            <router-link to="/multi-org/organization-selector" class="manage-link">
              <el-icon><Setting /></el-icon>
              管理组织
            </router-link>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import { OfficeBuilding, ArrowDown, Setting } from '@element-plus/icons-vue'
import { organizationAPI } from '@/api/organization'
import { useAppStore } from '@/stores/appStore'

const appStore = useAppStore()

// 使用store中的数据作为计算属性
const storeUserOrganizations = computed(() => appStore.userOrganizations)
const storeCurrentOrganization = computed(() => appStore.currentOrganization)
const userRoles = ref<Map<number, string>>(new Map())

// 获取用户所属的组织
const loadUserOrganizations = async () => {
  try {
    // 组织信息已经通过store加载，这里只需要获取用户在各组织中的角色
    if (appStore.userOrganizations.length > 0) {
      // 获取用户在各组织中的角色
      await Promise.all(appStore.userOrganizations.map(async (org: any) => {
        try {
          const roleResponse: any = await organizationAPI.getUserRoleInOrganization(
            appStore.user?.id || 0, 
            org.id
          );
          if (roleResponse.success) {
            userRoles.value.set(org.id, roleResponse.data.role || '成员');
          }
        } catch (error) {
          console.error(`获取组织${org.id}中的角色失败:`, error);
        }
      }));
    }
  } catch (error) {
    console.error('加载用户组织角色失败:', error);
    ElMessage.error('加载用户组织角色失败');
  }
}

// 处理组织切换
const handleOrganizationChange = (organizationId: string) => {
  const org = appStore.userOrganizations.find((o: any) => o.id === parseInt(organizationId))
  if (org) {
    appStore.setCurrentOrganization(org)
    localStorage.setItem('currentOrganization', JSON.stringify(org))
    ElMessage.success(`已切换到组织: ${org.name}`)
    
    // 刷新当前页面数据
    window.location.reload()
  }
}

// 获取用户在组织中的角色
const getUserRoleInOrganization = (organizationId: number) => {
  return userRoles.value.get(organizationId) || '成员'
}

// 生命周期
onMounted(() => {
  loadUserOrganizations();
})
</script>

<style scoped>
.organization-switcher {
  margin-right: 16px;
}

.organization-button {
  display: flex;
  align-items: center;
  gap: 8px;
}

.organization-name {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.organization-dropdown {
  max-height: 300px;
  overflow-y: auto;
}

.organization-dropdown-item {
  padding: 8px 16px;
}

.org-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.org-avatar {
  flex-shrink: 0;
}

.org-info {
  flex: 1;
  min-width: 0;
}

.org-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.org-role {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.manage-link {
  display: flex;
  align-items: center;
  gap: 5px;
  text-decoration: none;
  color: inherit;
}
</style>